package com.memory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.memory.common.BaseContext;
import com.memory.common.R;
import com.memory.daomain.*;
import com.memory.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author 邓哈哈
 * 2023/2/2 19:58
 * Function:
 * Version 1.0
 */

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 支付订单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //获得当前用户id
        Long currentId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);

        //查询当前用户数据
        User user = userService.getById(currentId);

        //查询当前用户地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        //向订单表(一条数据)和订单明细表插入数据(多条数据)

        long orderId = IdWorker.getId();//自动生成订单号
        AtomicInteger amount = new AtomicInteger(0);//总金额

        //遍历购物车,获取订单明细数据,同时累加金额得到总金额
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setOrderId(orderId);//订单id
            orderDetail.setNumber(item.getNumber());//数量
            orderDetail.setDishFlavor(item.getDishFlavor());//订单口味
            orderDetail.setDishId(item.getDishId());//菜品id
            orderDetail.setSetmealId(item.getSetmealId());//套餐id
            orderDetail.setName(item.getName());//订单名称
            orderDetail.setImage(item.getImage());//订单图片
            orderDetail.setAmount(item.getAmount());//订单金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());//累加金额
            return orderDetail;
        }).collect(Collectors.toList());

        //获得订单数据
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setStatus(2);//派送中
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(currentId);//下单用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//下单用户姓名
        orders.setConsignee(addressBook.getConsignee());//收件人
        orders.setPhone(addressBook.getPhone());//收件人电话
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())//省
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())//城市
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()//区
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail())));//细节

        //插入订单
        boolean save = orderService.save(orders);

        //插入订单明细
        boolean saveBatch = orderDetailService.saveBatch(orderDetailList);

        //清空购物车
        boolean remove = shoppingCartService.remove(lqw);

        return save && saveBatch && remove ? R.success("下单成功!") : R.error("下单失败");
    }

    /**
     * 查看已支付的订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<Orders>> getPage(Integer page, Integer pageSize) {
        Page<Orders> orderPage = orderService.getPage(page, pageSize);

        return orderPage != null ? R.success(orderPage) : R.error("订单显示失败");
    }
}
